/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package jtmcraft.game;

import jtmcraft.game.command.Command;
import java.awt.Image;
import java.util.ArrayList;
import java.util.EnumMap;
import jtmcraft.graphics.ImageResourceFactory;
import jtmcraft.graphics.ImageResourceFactory.eImageResource;

/**
 *
 * @author tom
 */
public class CommandButton {

    public enum ButtonState
    {
        Normal,
        MoveOver,
        Push
        ;

    }

    private ArrayList< Command > commandList;
    private ButtonState state;
    private EnumMap< ButtonState, Image > enumImage = new EnumMap<ButtonState, Image>(ButtonState.class);

    private int loopCount = 0;
    private int loopDelay = 10;

    private int x = 0;
    private int y = 0;

    public CommandButton( eImageResource normal, eImageResource mouseOver, eImageResource push ) {
        enumImage.put( ButtonState.Normal, ImageResourceFactory.getInstance().getImage( normal ) );
        enumImage.put( ButtonState.MoveOver, ImageResourceFactory.getInstance().getImage( mouseOver ) );
        enumImage.put( ButtonState.Push, ImageResourceFactory.getInstance().getImage( push ) );
        state = ButtonState.Normal;
    }

    public void addCommand( Command command)
    {
        if( commandList == null ) {
            commandList = new ArrayList<Command>();
        }
        
        commandList.add(command);
    }
    
    public ButtonState getState() {
        return state;
    }

    public void setState(ButtonState state) {
        this.state = state;
        if( state.equals( ButtonState.Push ) )
        {
           loopCount = loopDelay;
        }
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getWidth()
    {
        return enumImage.get( state ).getWidth(null);
    }

    public int getHeigth()
    {
        return enumImage.get( state ).getHeight(null);
    }

    public Image getImage()
    {
        return enumImage.get( state );
    }

    public void update()
    {
        if( loopCount-- < 1 && state.equals( ButtonState.Push ) )
        {
            loopCount = 0;
            setState( ButtonState.Normal );
        }
    }
   
    public boolean hitTest( int x, int y ) {

        return (
            ( x >= this.x && x <= (this.x+this.getWidth()) ) &&
            ( y >= this.y && y <= (this.y+this.getHeigth()) )
        );
    }
    
    public void fireCommand()
    {
        if( commandList != null )
        {
            for( Command command : commandList )
            {
                command.execute();
            }
        }
    }
}
